import { onShow } from '@dcloudio/uni-app'
import { useCartStore } from '../stores/cart'
import { useUserStore } from '../stores/user'
import { watch } from 'vue'

export const useFormat = () => {
	const formatPrice = (price : number) => {
		return price.toFixed(2)
	}

	const formatDate = () => {
		return 'YYYY-MM-DD'
	}

	return {
		formatPrice,
		formatDate
	}
}

export const useTotalCount = () => {
	const store = useCartStore()

	onShow(() => {
		setTabBarItemBadge()
	})

	watch(() => store.totalCount, () => {
		setTabBarItemBadge()
	})

	const setTabBarItemBadge = () => {
		if (store.totalCount > 0) {
			uni.setTabBarBadge({
				index: 2,
				text: store.totalCount + ''
			})
		} else {
			uni.removeTabBarBadge({
				index: 2
			})
		}
	}
}

export const useCheckRight = () => {
	onShow(() => {
		const store = useUserStore()

		if (!store.token) {
			uni.redirectTo({
				url: '/subpkg/login/login'
			})
		}
	})
}

export const useTabBarItemText = () => {
	onShow(() => {
		const store = useUserStore()

		if (store.token) {
			uni.setTabBarItem({
				index: 3,
				text: '我的'
			})
		} else {
			uni.setTabBarItem({
				index: 3,
				text: '未登录'
			})
		}
	})
}